import * as echarts from '../ec-canvas/echarts';
var cf = require("../../../config.js");
var cf3 = require("../../../utils/config3");
var util = require("../../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var baseHandle = require("../../template/baseHandle.js");
//获取应用实例
var app = getApp();

Page(Object.assign({}, baseHandle, {

  /**
   * 页面的初始数据
   */
  data: {
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    app: app,
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.userImagePath,
    srcTxt:"",
    list: [],
    isReloadList:false,
    inAction:1,
    hdTypeListShow:false,
    hdTypeActive:"1",
    showReferralsBtn: false,
    hdTypeActiveName:"雷达信息",
    isLoading: false,
    pageSize: 10,
    curPage: 1,
    isBottom: false,

    fList: [],
    fIsLoading: false,
    fCurPage: 1,
    fIsBottom: false,
    customInfo:{},
    activeTab:"hd",
    ecInt:{
      // 将 lazyLoad 设为 true 后，需要手动初始化图表
      lazyLoad: true
      // onInit: tChartx
    },
    interestData:{},
    ecActive: {
      lazyLoad: true
    },
    ecActiveData:{

    },
    ecInteraction:{
      lazyLoad: true
    },
    ecInteractionData: {
      list:[]
    },
    hideOp:0,
    curUser:{},
    member:{},
    lastVisit:"--",
    refreshingAvator:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
    var that = this;
    this.interestComponent = this.selectComponent('#mychart-dom-pie');
    this.activeComponent = this.selectComponent('#mychart-dom-line');
    this.interactionComponent = this.selectComponent('#mychart-dom-bar');
    app.getUserInfo(this, options, function (userInfo, res) {
      cusmallToken = wx.getStorageSync('cusmallToken');
      that.setData({
        openId: options.openid || "",
        eOpenId: options.eOpenId || "",
        hideOp: options.hideOp || 0,
        srcTxt: util.getCardSource(options.src),
        eId: options.eId,// 这个客户关联的销售员的 eid
      });
      that.getCusUserInfo();
      that.queryFormList();
      that.queryList();
      that.getBehaviorSwitch();
    });
  },
  changeTab(e){
    var ctx = this;
    var tab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab: tab
    });
    
    if ("info" == tab) {
    	ctx.getCustomerInfo();
    }
    
    if ("aifx" == tab){
      console.log("aifx");
      ctx.initInterest();
      ctx.initActive();
      ctx.initInteraction();
    }
  },
  judgeReferrals() {
    let eip = wx.getStorageSync("employee");
    let that = this;
    if (this.data.curUser.sourceInfo == '来自扫描' && eip) {
      var pageDomain = cf3.config.pageDomain.replace(/wechat-open/,'')
      wx.request({
        url: pageDomain+ "user-service/user/orgPerson/queryOrgPersonById",
        method: 'POST',
        data: {
          condition: eip.phone,
          status: 1,
          orgStatus:1
        },
        header: {
          'token': wx.getStorageSync('authName')
        },
        success: function (res) {
          if (res.data.rows.length>0) {
            that.setData({
              showReferralsBtn: true
            })
          }
        }
      })
    }
    
  },
  extendHd(e){
    var ctx = this;
    ctx.setData({
      hdTypeListShow: !ctx.data.hdTypeListShow
    });
  },
  getCusUserInfo(){
    let ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/memberrelation/findRelation",
      data: {
        cusmallToken: cusmallToken,
        mOpenId: ctx.data.openId,
        eOpenId: ctx.data.eOpenId,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data,name='';
        if (data && 0 === data.ret) {
          if (data.model.result){
            data.model.result.createTimeF = util.formatTime(new Date(data.model.result.createTime));
              var lastVisitTime = util.formatTime(new Date(data.model.result.lastBrowserTime));
            ctx.setData({
              lastVisit: lastVisitTime,
              curUser:data.model.result,
              mid: data.model.result.memberId,
              srcTxt: util.getCardSource(data.model.result.source),
              state:data.model.result.state,
              toEmployeeName:data.model.result.toEmployeeName
            });
          }
          if(data.model.result.memberExinfo){
            name = JSON.parse(data.model.result.memberExinfo).name
          }
          if(data.model.member){
            data.model.member.name = name
            ctx.setData({
              member: data.model.member    
            });
          }
          ctx.judgeReferrals()
        }else{
          wx.showToast({
            title: data.msg,
            icon:"none"
          })
        }
      },
      fail() {

      },
      complete() {
        ctx.interest();
        ctx.activeTrend();
        ctx.interaction();
      }
    });
  },
  getCustomerInfo() {
	  var ctx = this;
	  wx.request({
		  url: cf.config.pageDomain + "/applet/mobile/visitcard/memberrelation/findMemberExinfo",
		  data: {
			  cusmallToken: cusmallToken,
			  openid: ctx.data.openId
		  },
		  header: {
			  'content-type': 'application/json'
		  },
		  success: function (res) {
			  ctx.setData({
				 customInfo: res.data.model.record
			  });
		  }
	  })
  },
  hdFetchList(e){
    var ctx = this;
    var hdType = e.currentTarget.dataset.hdtype;
    var hdTypeActiveName = "";
    switch(hdType){
      case "1":
        hdTypeActiveName = "雷达信息";
      break;
      case "2":
        hdTypeActiveName = "雷达互动";
      break;
      case "3":
        hdTypeActiveName = "跟进记录";
      break;
    }
    ctx.setData({
      hdTypeActiveName:hdTypeActiveName,
      hdTypeActive: hdType,
      inAction: parseInt(hdType),
      list:[],
      curPage:1,
      isBottom:false,
      activeTab: "hd"
    });
    ctx.queryList();
  },
  queryList() {//

    var ctx = this;
    if (ctx.data.isLoading || ctx.data.isBottom) {
      return;
    }
    wx.showLoading({
      title: '加载中'
    });
    ctx.setData({ isLoading: true });
    wx.request({
      url: cf.config.pageDomain +"/applet/mobile/visitcard/bahavior/queryMemberBehaviorTrail",
      data: {
        cusmallToken: cusmallToken,
        openId: ctx.data.openId,
        eid: ctx.data.eId,
        action: ctx.data.inAction,
        start: (ctx.data.curPage - 1) * ctx.data.pageSize,
        limit: ctx.data.pageSize,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          var list = data.model.list;
          for(let item of list){
            item.behaviorTxt = util.behaviorType(item.type, item.count)
            item.behaviorTime = util.timestampToDayHkt(item.createTime);
            // if (item.sttr1 && item.sttr1.length > 10) {
            //   item.sttr1 = item.sttr1.substring(0, 6) + "...";
            // }
            if(-1 == item.type){
              item.sttr2 = item.sttr2.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g, ' ')
            }
          }
          list = ctx.data.list.concat(list);
          ctx.setData({
            list: list,
            memberExinfo:data.model.memberExinfo
          
          });
          if (data.model.total == ctx.data.list.length) {
            ctx.setData({
              isBottom: true
            });
          }
        } else {

        }
      },
      fail() {

      },
      complete() {
        ctx.setData({ isLoading: false });
        wx.hideLoading();
      }
    });
  },
  toFollow(){
    var ctx = this;
    wx.navigateTo({
      url: './follow?eId=' + ctx.data.eId + "&openId=" + ctx.data.openId,
    })
  },
  queryFormList(){
    var ctx = this;
    if (ctx.data.fIsLoading || ctx.data.fIsBottom) {
      return;
    }
    wx.showLoading({
      title: '加载中'
    });
    ctx.setData({ fIsLoading: true });
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/form/queryFormRecords",
      data: {
        cusmallToken: cusmallToken,
        openid: ctx.data.openId,
        eid: ctx.data.eId,
        start: (ctx.data.fCurPage - 1) * ctx.data.pageSize,
        limit: ctx.data.pageSize,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          var list = data.model.records;
          var forms = data.model.forms;
          var formsMap = {};
          for (let item of list) {
            item.createTimeF = util.formatTime(new Date(item.createTime))
          }
          for (let item of forms){
            formsMap[item.id] = {
              name: util.cusSubString(item.name, 10),
              orgName: item.name
            };
          }
          list = ctx.data.fList.concat(list);

          ctx.setData({
            fList: list,
            formsMap: formsMap
          });
          if (data.model.total == ctx.data.fList.length) {
            ctx.setData({
              fIsBottom: true
            });
          }
        } else {

        }
      },
      fail() {

      },
      complete() {
        ctx.setData({ fIsLoading: false });
        wx.hideLoading();
      }
    });
  },
  interest() {//ai分析 兴趣统计
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/interest",
      data: {
        cusmallToken: cusmallToken,
        mid: ctx.data.mid,
        eid: ctx.data.eId,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          ctx.setData({
            interestData:{
              toCompanyPerD: data.model.toCompanyPerD,
              toMePerD: data.model.toMePerD,
              toProductPerD: data.model.toProductPerD
            }
          });
        } else {
          ctx.setData({
            interestData: {
              toCompanyPerD: 33.33,
              toMePerD: 33.33,
              toProductPerD: 33.33
            }
          });
        }
      },
      fail() {

      },
      complete() {
      }
    });
  },
  initInterest(data){
    let ctx = this;
    this.interestComponent.init((canvas, width, height) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      ctx.setInterestOption(chart);

      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart = chart;

      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },
  setInterestOption(chart) {

    let ctx = this;
    var option = {
      color: ["#FF5722", "#FF9800", "#00BCD4"],
      legend: {
        itemWidth: 10,
        itemHeight: 10,
        selectedMode: false,
        orient: 'horizontal',
        bottom: 40,
        data: ["对我感兴趣", "对产品感兴趣","对公司感兴趣"]
      },
      series: [{
        label: {
          normal: {
            fontSize: 14,
            formatter: "{d}%",
            color:"#000000"
          }
        },
        type: 'pie',
        center: ['50%', '40%'],
        radius: [0, '60%'],
        data: [{
          value: ctx.data.interestData.toMePerD,
          name: '对我感兴趣'
        }, {
            value: ctx.data.interestData.toProductPerD,
          name: '对产品感兴趣'
        },{
            value: ctx.data.interestData.toCompanyPerD,
          name: '对公司感兴趣'
        },
        ],
      
        itemStyle: {
          emphasis: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 2, 2, 0.3)'
          }
        }
      }]
    };

    chart.setOption(option);
  },
  toReferrals() {
    wx.navigateTo({
      url:`/subPackages2/pages/recommend/recommend?customerName=${this.data.member.nickName ||this.data.member.name }&customerMobile=${this.data.member.tel}`
    })
  },
  activeTrend() {//客户最近天数活跃度趋势统计
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/activeTrend",
      data: {
        cusmallToken: cusmallToken,
        mid: ctx.data.mid,
        eid: ctx.data.eId,
        dayNum: 15
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          var activeNum = [];
          var activeDay = [];
          for(let item of data.model.list){
            activeNum.push(item.activeNum);
            activeDay.push(item.day.substring(5));
          }
          ctx.setData({
            ecActiveData:{
              activeNum: activeNum.reverse(),
              activeDay: activeDay.reverse()
            }
          })
        } else {

        }
      },
      fail() {

      },
      complete() {
      }
    });

  },
  initActive(data) {
    let ctx = this;
    this.activeComponent.init((canvas, width, height) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      ctx.setActiveOption(chart);

      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart = chart;

      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },
  setActiveOption(chart) {
    let ctx = this;
    var option = {
      title: {
        text: '',
        left: 'center'
      },
      color: ["#37A2DA"],
      
      grid: {
        top: "10%",
        containLabel: true
      },

      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ctx.data.ecActiveData.activeDay,
      },
      yAxis: {
        x: 'center',
        type: 'value',
        splitLine: {
          lineStyle: {
            type: 'solid'
          }
        },
        min: 0
      },
      series: [{
        // name: labelName,
        type: 'line',
        smooth: true,
        data: ctx.data.ecActiveData.activeNum
      }]
    };

    chart.setOption(option);
  },
  interaction() {//客户互动数据
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/interaction",
      data: {
        cusmallToken: cusmallToken,
        mid: ctx.data.mid,
        eid: ctx.data.eId,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          ctx.setData({
            ecInteractionData:{
              list: [data.model.thumbs, 
              data.model.comment, data.model.askGoods, data.model.forward, data.model.call, data.model.save,data.model.addMemory]
            }
          })
        } else {

        }
      },
      fail() {

      },
      complete() {
      }
    });

  },
  initInteraction(data) {
    let ctx = this;
    this.interactionComponent.init((canvas, width, height) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      ctx.setInteractionOption(chart);

      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart = chart;

      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },
  setInteractionOption(chart){
    let ctx = this;
    var option = {
      title: {
        text: '',
        left: 'center'
      },

      grid: {
        top:"10%",
        containLabel: true
      },

      xAxis: {
        type: 'value',
        axisLine: {
          lineStyle: {
            color: '#999'
          }
        },
        axisLabel: {
          color: '#666'
        }
      },
      yAxis: 
        {
          type: 'category',
          axisTick: { show: false },
          data: ['点赞', '评论', '咨询产品', '转发', '拨打电话', '保存电话', '印象标签'],
          axisLine: {
            lineStyle: {
              color: '#999'
            }
          },
          axisLabel: {
            color: '#666'
          }
        }
      ,
      series: [{
          smooth: true,
          type: 'bar',
          label: {
            normal: {
              show: true,
              position: 'inside'
            }
          },
        data: ctx.data.ecInteractionData.list,
          itemStyle: {
            normal:{
              color: function (params) {
                var colorList = ["#FF5722", 
                "#00BCD4", "#9E9E9E", "#616161", "#795548","#009688", "#FF9800"];
                return colorList[params.dataIndex];
              }
            }
            // emphasis: {
            //   color: '#37a2da'
            // }
          }
        }]
    };

    chart.setOption(option);
  },
  gotoChat:function(){
    var toEmployeeName=this.data.toEmployeeName;
    if(this.data.state==3){
      wx.showToast({
        title: '用户已被交接给'+toEmployeeName,
        icon: 'none',
        duration: 2000
      })

      return;
    }
    var url = "/subPackages/pages/chat/chat?selToID=" + this.data.openId + '&nickName=' + this.data.member.nickName;
    wx.navigateTo({
      url: url,
    })
  },
  editInfo:function(){
	  var url = "/pages/sales/custom_detail/edit_customer?eOpenId="+ this.data.eOpenId +"&openId=" + this.data.openId;
	  wx.navigateTo({
		 url: url 
	  });
  },
  phoneCall:function(e){
    var phoneNum = e.currentTarget.dataset.phone;
    if(phoneNum){
      wx.makePhoneCall({
        phoneNumber: phoneNum,
      })
    }
  },
  closeSome:function(e){
    if ("hdtype" !=e.target.dataset.tab){
	    this.setData({
	      hdTypeListShow:false
	    });
    }
  },
  /**
   * 雷达消息是否被屏蔽
   */
  getBehaviorSwitch(){
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/memberrelation/getBehaviorSwitch",
      data: {
        cusmallToken: cusmallToken,
        eid: ctx.data.eId,
        openid: ctx.data.openId
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          ctx.setData({
            behaviorSwitch: data.model.behaviorSwitch
          });
        } else {
          wx.showToast({
            title: data.msg,
            icon: "none"
          });
        }
      },
      fail() {

      },
      complete() {
      }
    });
  },
  changeRadar(){
    var title = "屏蔽雷达消息", content = "屏蔽后该用户雷达信息不出现在\"雷达\"页信息列表,且不推送雷达消息通知";
    var ctx = this;
    if (!ctx.data.behaviorSwitch){
      title = "取消屏蔽消息";
      content = "取消屏蔽后该用户雷达信息正常显示雷达页面，可正常接收用户雷达消息提醒";
    }
    wx.showModal({
      title: title,
      content: content,
      success(res) {
        if (res.confirm) {
          wx.request({
            url: cf.config.pageDomain + "/applet/mobile/visitcard/memberrelation/setBehaviorSwitch",
            data: {
              cusmallToken: cusmallToken,
              eid: ctx.data.eId,
              openid: ctx.data.openId
            },
            header: {
              'content-type': 'application/json'
            },
            success: function (res) {
              var data = res.data;
              if (data && 0 === data.ret) {
                wx.showToast({
                  title: '设置成功',
                  icon: "none"
                });
                ctx.setData({
                  behaviorSwitch: !ctx.data.behaviorSwitch
                });
              } else {
                wx.showToast({
                  title: data.msg,
                  icon: "none"
                });
              }
            },
            fail() {

            },
            complete() {
            }
          });
        }
      }
    });
  },
  handleRefreshAva(){
    let ctx = this;
    ctx.setData({
      refreshingAvator:true
    });
    setTimeout(function(){
      ctx.setData({
        refreshingAvator: false
      });
    },2000);
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/member/flashMemberInfo",
      data: {
        cusmallToken: cusmallToken,
        openid: ctx.data.openId,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          var member = ctx.data.member;
          member.nickName = data.model.nickName;
          member.headImgUrl = data.model.headPic;
          ctx.setData({
            member: member
          });
          wx.showToast({
            title: '信息已更新',
            icon: "none"
          })
        }else{
          wx.showToast({
            title: data.msg,
            icon:"none"
          })
        }
      },
      fail() {

      },
      complete() {
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var ctx = this;
    if (ctx.data.isReloadList){
      ctx.setData({
        list: [],
        curPage: 1,
        isBottom: false,
        isReloadList:false
      });
      ctx.queryList();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let ctx = this;
    if (!ctx.data.isLoading || "hd" == ctx.data.tab) {
      ctx.setData({ curPage: ctx.data.curPage + 1 });
      ctx.queryList();
    } else if (!ctx.data.fIsLoading || "form" == ctx.data.tab){
      ctx.setData({ curPage: ctx.data.fCurPage + 1 });
      ctx.queryFormList();
    }
    
  },

  /**
   * 用户点击右上角
   */
  onShareAppMessage: function () {

  }
}))